package com.example.nick.bodyapplication.ble

import android.Manifest
import android.R.string
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.bluetooth.le.BluetoothLeAdvertiser
import android.content.Context
import android.os.Bundle
import android.os.ParcelUuid
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.nick.bodyapplication.R
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
import java.util.*
import kotlin.experimental.and


class BleActivity : AppCompatActivity(), PermissionCallbacks {

    var mBluetoothLeAdvertiser: BluetoothLeAdvertiser? = null
    var mBluetoothManager: BluetoothManager? = null
    var mBluetoothAdapter: BluetoothAdapter? = null
    val mAdvertiseCallback = daqiAdvertiseCallback()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ble)
        requestPermissions()


    }

    class daqiAdvertiseCallback : AdvertiseCallback() {
        //开启广播成功回调
        override fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
            super.onStartSuccess(settingsInEffect)
            Log.d("daqi", "开启服务成功")
        }

        //无法启动广播回调。
        override fun onStartFailure(errorCode: Int) {
            super.onStartFailure(errorCode)
            Log.d("daqi", "开启服务失败，失败码 = $errorCode")
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {}
    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {}
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    private val REQUEST_PERMISSIONS_CODE = 1000
    fun requestPermissions(): Boolean {
        val perms = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
        )
        if (!EasyPermissions.hasPermissions(this, *perms)) {
            EasyPermissions.requestPermissions(
                this,
                "request location permission",
                REQUEST_PERMISSIONS_CODE,
                *perms
            )
            return true
        }
        return false
    }


    fun onStartBroadcast(view: View) {
        //初始化广播设置
        val mAdvertiseSettings = AdvertiseSettings.Builder() //设置广播模式，以控制广播的功率和延迟。
            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER) //发射功率级别
            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH) //不得超过180000毫秒。值为0将禁用时间限制。
            .setTimeout(3000) //设置是否可以连接
            .setConnectable(false)
            .build()

        //初始化广播包
        val mAdvertiseData = AdvertiseData.Builder()
            //设置广播设备名称
            .setIncludeDeviceName(true)
            //设置发射功率级别
//            .setIncludeDeviceName(true)
            .build()

        //初始化扫描响应包
        val mScanResponseData = AdvertiseData.Builder()
            //隐藏广播设备名称
//            .setIncludeDeviceName(false)
            //隐藏发射功率级别
            .setIncludeDeviceName(true)
            //设置广播的服务`UUID`
//            .addServiceUuid(ParcelUuid(UUID.fromString("0000fff7-0000-1000-8000-00805f9b34fb")))
            .addServiceUuid(ParcelUuid(UUID.fromString("0000181c-0000-1000-8000-00805f9b34fb")))
            //设置厂商数据
            .addManufacturerData(0x11, hexStr2Bytes("abcdefg"))
            .build()


        //获取蓝牙设配器
        mBluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        mBluetoothAdapter = mBluetoothManager!!.adapter
        //设置设备蓝牙名称
        mBluetoothAdapter!!.setName("daqi")

        //获取BLE广播的操作对象。
        //如果蓝牙关闭或此设备不支持蓝牙LE广播，则返回null。
        mBluetoothLeAdvertiser = mBluetoothAdapter!!.bluetoothLeAdvertiser
        //mBluetoothLeAdvertiser不为空，且蓝牙已开打
        if (mBluetoothAdapter!!.isEnabled()) {
            if (mBluetoothLeAdvertiser != null) {
                //开启广播
                mBluetoothLeAdvertiser!!.startAdvertising(
                    mAdvertiseSettings,
                    mAdvertiseData, mScanResponseData, mAdvertiseCallback
                )
            } else {
                Log.d("daqi", "该手机不支持ble广播")
            }
        } else {
            Log.d("daqi", "手机蓝牙未开启")
        }
    }

    fun onStopBroadcast(view: View) {
        mBluetoothLeAdvertiser?.stopAdvertising(mAdvertiseCallback)
    }

    /**
     * 十六进制字符串转换为byte[]
     *
     * @param hexStr 需要转换为byte[]的字符串
     * @return 转换后的byte[]
     */
    fun hexStr2Bytes(hexStr: String): ByteArray {
        /*对输入值进行规范化整理*/
        var hexStr = hexStr
        hexStr = hexStr.trim { it <= ' ' }.replace(" ", "").toUpperCase(Locale.US)
        //处理值初始化
        var m = 0
        var n = 0
        val iLen = hexStr.length / 2 //计算长度
        val ret = ByteArray(iLen) //分配存储空间
        for (i in 0 until iLen) {
            m = i * 2 + 1
            n = m + 1
            ret[i] =
                (Integer.decode(
                    "0x" + hexStr.substring(i * 2, m) + hexStr.substring(
                        m,
                        n
                    )
                ) and 0xFF).toByte()
        }
        return ret
    }


    /**
     * byte[]转换为十六进制字符串
     *
     * @param bytes 需要转换为字符串的byte[]
     * @return 转换后的十六进制字符串
     */
    fun byte2HexStr(bytes: ByteArray): String? {
        var hs = ""
        var stmp = ""
        for (n in bytes.indices) {
            stmp = Integer.toHexString((bytes[n] and 0XFF.toByte()).toInt())
            hs = if (stmp.length == 1) hs + "0" + stmp else hs + stmp
        }
        return hs
    }

}